/**
 * 文件名：FileUtil.java
 * 创建日期： 2012-5-30
 * Copyright (c) 2011-2011 广电运通
 * All rights reserved.
 
 * 修改记录：
 * 1.修改时间, 修改人：
 *   修改内容：
 */
package com.ehotting.eaf.core;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;

/**
 * @author Ansun
 * 
 */
public class FileHelper {

	private static Logger log = LoggerFactory.getLogger(FileHelper.class);

	/**
	 * 行分隔符
	 */
	public final static String LINE_SEPARATOR = System.getProperty("line.separator");

	// 复制文件
	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null) {
				inBuff.close();
			}
			if (outBuff != null) {
				outBuff.close();
			}
		}
	}

	public static void writeFile(String content, String path, String name) {
		log.info("path:{},name:{}",path,name);
		OutputStreamWriter oStreamWriter  = null;
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			oStreamWriter = new OutputStreamWriter(new FileOutputStream(path + File.separator + name),"utf-8") ;
			oStreamWriter.write(content);
			oStreamWriter.flush();
			log.info("文件写入成功");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oStreamWriter != null)
				try {
					oStreamWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	public static boolean writeXMLFile(String xmlContent, String path, String name,String encoding) {
		FileOutputStream fileOutputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			Document document = DocumentHelper.parseText(xmlContent);
			fileOutputStream = new FileOutputStream(path + File.separator + name);
			outputStreamWriter = new OutputStreamWriter(fileOutputStream,encoding);
			document.setXMLEncoding(encoding);
			document.write(outputStreamWriter);
			outputStreamWriter.flush();
			return true;
		} catch (IOException | DocumentException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outputStreamWriter != null) {
				try {
					outputStreamWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public static void writeFile(byte[] base64byte, String path, String name) {

		FileOutputStream fileOutputStream = null;
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			fileOutputStream = new FileOutputStream(path + File.separator + name);
			fileOutputStream.write(base64byte);
			fileOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null)
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	// 复制文件夹
	public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}

	/**
	 * 
	 * @param srcFileName
	 *            源文件
	 * @param destFileName
	 *            目标文件
	 * @param srcCoding
	 *            源文件字符集
	 * @param destCoding
	 *            目标文件字符集
	 * @throws IOException
	 *             IO异常
	 */
	public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding)
			throws IOException {// 把文件转换为GBK文件
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
			char[] cbuf = new char[1024 * 5];
			int len = cbuf.length;
			int off = 0;
			int ret = 0;
			while ((ret = br.read(cbuf, off, len)) > 0) {
				off += ret;
				len -= ret;
			}
			bw.write(cbuf, 0, off);
			bw.flush();
		} finally {
			if (br != null) {
				br.close();
			}
			if (bw != null) {
				bw.close();
			}
		}
	}

	/**
	 * 
	 * @param filepath
	 *            file path
	 * @throws IOException
	 */
	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}else if(f.exists()){
			f.delete();// 删除文件
		}
	}

	/**
	 * 删除目录，并且删除目录里面的文件，该操作只删除一级目录，不支持多目录
	 * 
	 * @param filepath
	 *            file path
	 * @throws IOException
	 */
	public static void delDir(String filepath) {
		File f = new File(filepath);// 定义文件路径

		// 1、先删除文件
		if (f.exists() && f.isDirectory() && f.listFiles().length > 0) {// 判断是文件还是目录
			File delFile[] = f.listFiles();
			int i = f.listFiles().length;
			for (int j = 0; j < i; j++) {
				if (delFile[j].isDirectory()) {
					delDir(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
				}
				delFile[j].delete();// 删除文件
			}
		}

		// 2、删除目录
		if (f.exists() && f.isDirectory() && f.listFiles().length == 0) {
			// 若有则把文件放进数组，并判断是否有下级目录
			f.delete();
		}
	}

	public static void deleteFile(String filepath) {
		File file = new File(filepath);// 定义文件路径
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 建一个目录
	 * 
	 * @param file
	 */
	public static boolean createDirectory(File file) {
		if (file.exists())
			return true;
		return file.mkdirs();
	}

	/**
	 * 创建目录
	 * 
	 * @param dirname
	 *            路径名称
	 * @return
	 */
	public static boolean createDirectory(String dirname) {
		return createDirectory(new File(dirname));
	}

	/**
	 * 判断文件、目录存在
	 * 
	 * @param path
	 *            路径 存在返回 true，不存在 返回false;
	 */
	public static boolean checkFileExists(String path) {
		if (StringHelper.isEmpty(path)) {
			return false;
		}
		if (new File(path).exists())
			return true;
		return false;
	}

	/***
	 * 获取当前目录下的文件
	 * 
	 * @Title: getFileList @Description: TODO(这里用一句话描述这个方法的作用) @param @param
	 * path @param @throws Exception 设定文件 @return void 返回类型 @throws
	 */
	public final static List<String> getFileList(String path) {
		List<String> list = new ArrayList<String>();
		File dir = new File(path);
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (int i = 0; i < fs.length; i++) {
				if (fs[i].isDirectory()) {
					List<String> subList = getFileList(fs[i].getAbsolutePath());
					list.addAll(subList);
				} else {
					list.add(fs[i].getAbsolutePath());
				}
			}
		}
		return list;
	}

	/***
	 * 获取当前目录下的一级文件名，不包括子目录文件
	 * 
	 * @param path
	 * @return
	 */
	public final static List<String> getChildFileList(String path) {
		List<String> list = new ArrayList<String>();
		File dir = new File(path);
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (int i = 0; i < fs.length; i++) {
				list.add(fs[i].getName());
			}
		}
		return list;
	}

	/**
	 * @throws Exception * 文件复制
	 * 
	 * @Title: copy @Description: TODO(这里用一句话描述这个方法的作用) @param @param fromPath
	 * 复制文件 @param @param toPath 粘贴文件 @return void 返回类型 @throws
	 */
	public final static void copy(String fromPath, String toPath) throws Exception {
		createDir(toPath);
		File file1 = new File(toPath);
		byte[] t = new byte[1024];
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(fromPath);
			out = new FileOutputStream(file1);
			int byteread = 0;
			while ((byteread = in.read(t)) != -1) {
				out.write(t, 0, byteread);
			}
		} catch (FileNotFoundException e) {
			log.error("file fromPath:" + fromPath + " to toPath:" + toPath, e);
			throw new Exception("file fromPath:" + fromPath + " to toPath:" + toPath);
		} catch (IOException e) {
			log.error("file fromPath:" + fromPath + " to toPath:" + toPath, e);
			throw new Exception("file fromPath:" + fromPath + " to toPath:" + toPath);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 
	 * @param str
	 *            字符串
	 * @param file
	 *            文件对象
	 * @throws IOException
	 *             io异常
	 */
	public static void appendFile(String file, String content) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(content);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 产生文件目录
	 * 
	 
	 * @return
	 */
	public static String mkdirYYYYMMDD(String absolutePath) {
		Date date = new Date();
		StringBuffer filePathBuf = new StringBuffer().append("/").append(DateHelper.toString(date, "yyyy")).append("/")
				.append(DateHelper.toString(date, "MM")).append("/").append(DateHelper.toString(date, "dd"))
				.append("/");
		String filePath = filePathBuf.toString();
		FileHelper.createDirectory(absolutePath + filePath);
		return filePath;
	}

	/**
	 * 产生文件目录
	 * 
	 
	 * @return
	 */
	public static String mkdirYYYYMMDD(String absolutePath, String context) {
		Date date = new Date();
		StringBuffer filePathBuf = new StringBuffer().append("/").append(context).append("/")
				.append(DateHelper.toString(date, "yyyy")).append("/").append(DateHelper.toString(date, "MM"))
				.append("/").append(DateHelper.toString(date, "dd")).append("/");
		String filePath = filePathBuf.toString();
		FileHelper.createDirectory(absolutePath + filePath);
		return filePath;
	}

	/**
	 * 产生文件目录
	 * 
	 
	 * @return
	 */
	public static String generateFileDir(String absolutePath, String extendFileName) {
		Date date = new Date();
		StringBuffer filePathBuf = new StringBuffer().append("/").append(DateHelper.toString(date, "yyyy")).append("/")
				.append(DateHelper.toString(date, "MM")).append("/").append(DateHelper.toString(date, "dd"))
				.append("/");
		String filePath = filePathBuf.toString();

		FileHelper.createDirectory(absolutePath + filePath);

		StringBuffer fileName = new StringBuffer(filePath).append(DateHelper.toString(date, "HHmmss")).append("_")
				.append((int) (Math.random() * 1000000)).append(".").append(extendFileName);
		return fileName.toString();
	}

	public static String generateFileName(String preFileName) {
		return preFileName + DateHelper.toStringYYYYMMDDHHmmss(new Date()) + StringHelper.getRandomString(6);
	}

	/**
	 * 文件重命名
	 * 
	 * @param path
	 *            文件目录
	 * @param oldname
	 *            原来的文件名
	 * @param newname
	 *            新文件名
	 */
	public static void renameFile(String path, String oldname, String newname) {
		if (!oldname.equals(newname)) {// 新的文件名和以前文件名不同时,才有必要进行重命名
			File oldfile = new File(path + "/" + oldname);
			File newfile = new File(path + "/" + newname);
			if (!oldfile.exists()) {
				return;// 重命名文件不存在
			}
			if (newfile.exists())// 若在该目录下已经有一个文件和新文件名相同，则不允许重命名
				log.info("fileName[" + newname + "] exist.");
			else {
				oldfile.renameTo(newfile);
			}
		} else {
			System.out.println("新文件名和旧文件名相同...");
		}
	}

	public static void changeFolderPermission(String root, String dir) {
		String[] paths = dir.split("/");
		String ss = "";
		for (String s : paths) {
			ss += "/" + s;
			changeFolderPermission(new File(root + ss));
		}
	}

	public static void changeFolderPermission(File dirFile) {
//		Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
//		perms.add(PosixFilePermission.OWNER_READ);
//		perms.add(PosixFilePermission.OWNER_WRITE);
//		perms.add(PosixFilePermission.OWNER_EXECUTE);
//		perms.add(PosixFilePermission.GROUP_READ);
//		perms.add(PosixFilePermission.GROUP_WRITE);
//		perms.add(PosixFilePermission.GROUP_EXECUTE);
//		perms.add(PosixFilePermission.OTHERS_READ);
//		perms.add(PosixFilePermission.OTHERS_WRITE);
//		perms.add(PosixFilePermission.OTHERS_EXECUTE);
//		try {
//			Path path = Paths.get(dirFile.getAbsolutePath());
//			Files.setPosixFilePermissions(path, perms);
//		} catch (Exception e) {
//			log.info("Change folder " + dirFile.getAbsolutePath() + " permission failed.", e);
//		}
	}

	// 得到某一目录下的所有文件夹
	public final static List<File> getAllDirList(String path) {
		List<File> list = new ArrayList<File>();
		File root = new File(path);
		File[] dirs = root.listFiles();
		if (dirs != null) {
			for (int i = 0; i < dirs.length; i++) {
				if (dirs[i].isDirectory()) {
					list.add(dirs[i]);
				}
				list.addAll(getAllDirList(dirs[i].getAbsolutePath()));
			}
		}
		return list;
	}

	/**
	 * 删除空的文件夹
	 * 
	 * @param list
	 */
	public static void removeNullDir(List<File> list) {
		for (int i = 0; i < list.size(); i++) {
			File temp = list.get(i);
			
			log.info("fileName:{},temp.listFiles().length:{}",temp.getAbsoluteFile(),temp.listFiles().length);
			if (temp.isDirectory() && temp.listFiles().length <= 0) {
				log.info("------------delete file:{}",temp.getAbsolutePath());
				temp.delete();
			}
		}
	}



	public static void  createDir(String file){
		if(file.indexOf(".")==-1){
			return;
		}
		String quote = Matcher.quoteReplacement(File.separator);
		if(file.indexOf(File.separator)>=0){
			quote = Matcher.quoteReplacement(File.separator);
		}else{
			quote = Matcher.quoteReplacement("/") ;
		}
		String[] array= file.split(quote);
		StringBuffer buf = new StringBuffer(file.length());
		for(int i=0;i<array.length-1;i++){
			String a = array[i];
			buf.append(a).append(File.separator);
		}
		File dir = new File(buf.toString());
		dir.mkdirs();

	}

	public static void main(String args[]) throws IOException {
		// // 源文件夹
		// String url1 = "D:/user/test/";
		// // 目标文件夹
		// String url2 = "D:/user/testcopy/";
		// // 创建目标文件夹
		// (new File(url2)).mkdirs();
		// // 获取源文件夹当前下的文件或目录
		// File[] file = (new File(url1)).listFiles();
		// for (int i = 0; i < file.length; i++) {
		// if (file[i].isFile()) {
		// // 复制文件
		// String type =
		// file[i].getName().substring(file[i].getName().lastIndexOf(".") + 1);
		//
		// if (type.equalsIgnoreCase("txt")) {
		// copyFile(file[i], new File(url2 + file[i].getName()),
		// AppCoreConstants.UTF8, AppCoreConstants.GBK);
		// } else {
		// copyFile(file[i], new File(url2 + file[i].getName()));
		// }
		// }
		// if (file[i].isDirectory()) {
		// // 复制目录
		// String sourceDir = url1 + File.separator + file[i].getName();
		// String targetDir = url2 + File.separator + file[i].getName();
		// copyDirectiory(sourceDir, targetDir);
		// }
		// }

		// List<String> list = FileUtil
		// .getFileList("D:\\temp\\Filegetatmfiles\\20140917\\ANSUN-PC_dcb01ddc23ea42c9939ce75bbfd808fd_1696546097e04fa4a2df82ff73ff3466_");
		// System.out.println(list);
		// for (String s : list) {
		// System.out.println(s);
		// }
		// System.out.println("ddd");
		// List<String> fileList =
		// FileHelper.getChildFileList("F:\\root\\robot\\patrol_stop\\");
		// for (String s : fileList) {
		// System.out.println(s);
		// }

//		boolean b = FileHelper
//				.checkFileExists("F:\\root\\robot\\patrol_stop\\patrol_400283095ec8fdc9015ec9398a090041.txt");
//		System.out.println("b:" + b);
		
		
		String ss = "/111/Patrol/2019/07/24/tv201907241144243H9HMX.jpg,/111/Patrol/2019/07/24/tv201907241130089C5HUC.jpg,/111/Patrol/2019/07/24/tv20190724111455XHT8JO.jpg,/111/Patrol/2019/07/24/tv20190724105940ZJ2B1Y.jpg,/111/Patrol/2019/07/23/tv20190723112835PUG0X9.jpg,/111/Patrol/2019/07/16/tv20190716190021EC0NKV.jpg,/111/Patrol/2019/05/21/tv20190521165725F4T0VL.jpg,/111/Patrol/2019/05/09/tv20190509111752ZJZCOW.jpg,/111/Patrol/2019/05/08/tv2019050817323807IKGV.jpg,/111/Patrol/2019/05/08/tv20190508171326RM6OA7.jpg,/111/Patrol/2019/05/08/tv201905081514173Z2JLS.jpg,/111/Patrol/2019/04/24/tv20190424173956JG5OVD.jpg,/111/Patrol/2019/04/23/tv20190423093007WHGGND.jpg,/111/Patrol/2019/04/22/tv20190422171038IVGJYI.jpg,/111/Patrol/2019/04/12/tv20190412113405JB81RG.jpg,/111/Patrol/2019/04/12/tv20190412112605ZL84VN.jpg,/111/Patrol/2019/04/12/tv20190412111724MPDDLU.jpg,/111/Patrol/2019/04/12/tv20190412111009KS53EQ.jpg,/111/Patrol/2019/04/12/tv20190412110113G9VG2N.jpg,/111/Patrol/2019/04/12/tv201904121051393Q2WQZ.jpg,/111/Patrol/2019/04/12/tv20190412104356G0N1RD.jpg,/111/Patrol/2019/04/12/tv201904121028024M3Z69.jpg,/111/Patrol/2019/04/12/tv20190412101527LUZMAJ.jpg,/111/Patrol/2019/04/11/tv20190411094645M4FMUS.jpg,/111/Patrol/2019/04/10/tv20190410102446Y7FPC3.jpg,/111/Patrol/2019/04/09/tv20190409174006C2RF14.jpg,/111/Patrol/2019/04/01/tv201904010943139Y8FEI.jpg,/111/Patrol/2019/03/31/tv20190331151354LE9FDK.jpg,/111/Patrol/2019/03/31/tv2019033114381938093S.jpg,/111/Patrol/2019/03/30/tv201903301743356GEKHU.jpg,/111/Patrol/2019/03/30/tv20190330171729JSUJVJ.jpg,/111/Patrol/2019/03/30/tv20190330165728IMD3DE.jpg,/111/Patrol/2019/03/30/tv20190330155119828CVL.jpg,/111/Patrol/2019/03/30/tv20190330152135P7944I.jpg,/111/Patrol/2019/03/30/tv201903301520243JXUOT.jpg,/111/Patrol/2019/03/30/tv20190330145445RLF1CG.jpg,/111/Patrol/2019/03/30/tv20190330144819S2OC5J.jpg,/111/Patrol/2019/03/30/tv20190330144718GLD0EI.jpg,/111/Patrol/2019/03/30/tv20190330144611LL2ZUY.jpg,/111/Patrol/2019/03/30/tv201903301444555SLIS8.jpg,/111/Patrol/2019/03/29/tv20190329114721YGY6K2.jpg,/111/Patrol/2019/03/29/tv20190329113813HZPSXC.jpg,/111/Patrol/2019/03/29/tv20190329112422XR8PNC.jpg,/111/Patrol/2019/03/28/tv20190328094736VWV692.jpg,/111/Patrol/2019/03/27/tv20190327101256501A7F.jpg";
		String[] s = ss.split(",");
		for(String i :s){
			FileHelper.copyFile(new File("E:\\home\\dky\\robot\\fileServer"+i), new File("E:\\home\\dky\\robot\\fileServer\\1\\"+i.substring(i.lastIndexOf("/")+1)));
		}
		

	}

}
